package Java_Concurrency_in_Practice.count_down_latch;

import java.util.concurrent.CountDownLatch;

/**
 * 闭锁是一种同步工具类, 它可以延迟线程的进度直到其到达终止状态.
 * 启动门使得主线程能够同时释放所有工作线程
 * 结束门则使得主线程能够等待最后一个线程执行完成
 * */
public class TestHarness {

	public long timeTaks(int nThreads, final Runnable task) throws InterruptedException {
		final CountDownLatch startGate = new CountDownLatch(1);
		final CountDownLatch endGate = new CountDownLatch(nThreads);
		
		for (int i = 0; i < nThreads; i++) {
			Thread t = new Thread() {
				public void run() {
					try {
						startGate.await();
						try {
							task.run();
						} finally {
							endGate.countDown();
						}
					} catch (InterruptedException ignore) {
						// nothing
					} 
				}
			};
			t.start();
		}
		
		long start = System.nanoTime();
		startGate.countDown();
		endGate.await();
		long end = System.nanoTime();
		return end - start;
	}
}
